package com.zjsru.leetcode75.level1;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: CookLee
 * @Date: 2022/10/30
 * 同构字符串:如果 s 中的字符可以按某种映射关系替换得到 t ，那么这两个字符串是同构的。
 * 输入：s = "egg", t = "add"
 * 输出：true
 *
 * 输入：s = "foo", t = "bar"
 * 输出：false
 */
public class IsIsomorphic {
    
    /**
     * 查找第一个下标出现次数
     */
    public boolean isIsomorphic(String s, String t) {
        for (int i = 0; i < s.length(); i++) {
            if (s.indexOf(s.charAt(i)) != t.indexOf(t.charAt(i))) {
                return false;
            }
        }
        return true;
    }
    
    /**
     * HashMap
     */
    public boolean isIsomorphic2(String s, String t) {
        Map<Character, Character> s2t = new HashMap<Character, Character>();
        Map<Character, Character> t2s = new HashMap<Character, Character>();
        int len = s.length();
        for (int i = 0; i < len; ++i) {
            char x = s.charAt(i), y = t.charAt(i);
            if ((s2t.containsKey(x) && s2t.get(x) != y) || (t2s.containsKey(y) && t2s.get(y) != x)) {
                return false;
            }
            s2t.put(x, y);
            t2s.put(y, x);
        }
        return true;
    }
    
    public static void main(String[] args) {
        IsIsomorphic isIsomorphic = new IsIsomorphic();
        String s = "egg";
        String t = "add";
        System.out.println(isIsomorphic.isIsomorphic2(s, t));
    }
}
